<template>
	<view class="container">
		<!-- <button class="sys_btn" open-type="getUserInfo" lang="zh_CN" @getuserinfo="appLoginWx">小程序登录授权</button> -->
			<!-- #ifdef MP -->
			<!-- <input class="ser-input" type="text" value="点击搜索" disabled @click="toSearch()" /> -->
			<!-- 新的搜索，不跳往搜索页面了 -->
			<view class="search">
				<input class="ser-input" type="text" placeholder="输入关键字搜索" v-model="searchKey" confirm-type="search" @confirm="toSearch" />
			</view>
			<!-- #endif -->
		<!-- 头部轮播 -->
		<view class="carousel-section">
			<!-- 标题栏和状态栏占位符 -->
			<!-- <view class="titleNview-placing"></view> -->
			<!-- 背景色区域 -->
			<!-- #ifndef MP -->
			<view class="titleNview-background" :style="{backgroundColor:titleNViewBackground}"></view>
			<!-- #endif -->
			<swiper class="carousel" circular autoplay="true" duration="1000" @change="swiperChange">
				<swiper-item v-for="(item, index) in carouselList" :key="index" class="carousel-item" @click="navToDetailPage({title: '轮播广告'})">
					<image :src="item.imgUrl" />
				</swiper-item>
			</swiper>
			
			<!-- 自定义swiper指示器 -->
			<view class="swiper-dots">
				<text class="num">{{swiperCurrent+1}}</text>
				<text class="sign">/</text>
				<text class="num">{{swiperLength}}</text>
			</view>
		</view>
		<!-- 分类 -->
		<view class="content">
			<view class="cate-section">
				<!-- <view @tap="navToList('新品推荐')" class="cate-item">
					<image src="/static/temp/shortcut-new.png"></image>
					<text>新品推荐</text>
				</view>
				<view @tap="navToList('热销市场')" class="cate-item">
					<image src="/static/temp/shortcut-hot.png"></image>
					<text>热销市场</text>
				</view>
				<view @tap="navToList('促销折扣')" class="cate-item">
					<image src="/static/temp/shortcut-discount.png"></image>
					<text>促销折扣</text>
				</view> -->
				<view class="cate-item" v-for="(item, index) in navBtn" :key="index">
					<image :src="item.imgUrl"></image>
					<text>{{item.title}}</text>
				</view>
			</view>
			
			<!-- 爆款楼层 -->
			<view class="seckill-section m-t">
				<view class="s-header"  @tap="navToList('热销推荐')">
					<image class="s-img" src="/static/icon-fire.png" mode="widthFix"></image>
					<text class="tip">热销推荐</text>
				</view>
			
				<scroll-view class="floor-list" scroll-x>
					<view class="scoll-wrapper">
						<view v-for="(goods, index) in seckillGoodsList" :key="index" class="floor-item" @click="navToDetailPage(goods.id)">
							<view class="image-wrapper">
								<image :src="goods.logo" :class="[goods.loaded]" mode="aspectFill" lazy-load @load="onImageLoad('seckillGoodsList', index)"
								 @error="onImageError('seckillGoodsList', index)"></image>
							</view>
							<text class="title clamp">{{goods.title}}</text>
							<text class="subtitle clamp">{{goods.price_cost}}</text>
							<text class="price">￥{{goods.price_market}}</text>
						</view>
					</view>
				</scroll-view>
			</view>
			
			
			<block>
				<!-- 分类推荐楼层 -->
				<view class="f-header m-t">
					<image src="/static/temp/h1.png"></image>
					<view class="tit-box">
						<text class="tit">热销推荐</text>
					</view>
					<!-- <text class="mallicon icon-you"></text> -->
				</view>
				<view class="class-floor">
					<view class="guess-section">
						<view v-for="(goods, index2) in seckillGoodsList" :key="index2" class="guess-item" @click="navToDetailPage(goods.id)">
							<view class="image-wrapper">
								<image :src="goods.logo" :class="[goods.loaded]" mode="aspectFill" lazy-load @load="onFloorImageLoad('mallGoodsList',index, index2)"
								 @error="onFloorImageError('mallGoodsList',index, index2)"></image>
							</view>
							<text class="title clamp">{{goods.title}}</text>
							<text class="subtitle clamp">型号：{{goods.price_cost}}</text>
							<text class="price">￥{{goods.price_market}}</text>
						</view>
					</view>
				</view>
			</block>
			
			<!-- <block v-for="(mallGoods,index) in mallGoodsList" :key="index"> -->
				<!-- 分类推荐楼层 -->
				<!-- <view class="f-header m-t"  @tap="navToList(mallGoods.GoodsClassName)">
					<image src="/static/temp/h1.png"></image>
					<view class="tit-box">
						<text class="tit">{{mallGoods.GoodsClassName}}</text>
					</view>
					<text class="mallicon icon-you"></text>
				</view>
				<view class="class-floor">
					<view class="guess-section">
						<view v-for="(goods, index2) in mallGoods.MallGoodsList" :key="index2" class="guess-item" @click="navToDetailPage(goods)">
							<view class="image-wrapper">
								<image :src="goods.DefaultPicURL" :class="[goods.loaded]" mode="aspectFill" lazy-load @load="onFloorImageLoad('mallGoodsList',index, index2)"
								 @error="onFloorImageError('mallGoodsList',index, index2)"></image>
							</view>
							<text class="title clamp">{{goods.GoodsName}}</text>
							<text class="subtitle clamp">型号：{{goods.GoodsModel}}</text>
							<text class="price">￥{{goods.Price}}</text>
						</view>
					</view>
				</view>
			</block> -->
		</view>
	</view>
</template>

<script>
	import bmap  from "@/lib/bmap-wx.js"
	export default {

		data() {
			return {
				searchKey:'',
				titleNViewBackground: 'rgb(245,95,113)',
				swiperCurrent: 0,
				swiperLength: 3,
				carouselList: [{
						imgUrl: "/static/banner-1.png",
						background: "rgb(245,95,113)",
					},
					{
						imgUrl: "/static/banner-2.png",
						background: "rgb(250,103,95)",
					},
					{
						imgUrl: "/static/banner-3.png",
						background: "rgb(250,123,49)",
					}
				],
				navBtn:[],//导航
				seckillGoodsList: [],
				mallGoodsList: []
			};
		},
		onLoad(){
			this.aaa();
			// this.getWxNews()
		},
		onShow() {
			var BMap = new bmap.BMapWX({ 
				ak: 'i0BXsy4TnbXQ51USDMHdlhoOb2kgEmrz'
			});
			var fail = function(data) { 
				console.log(JSON.stringify(data)) 
			}; 
			var success = function(data) { 
				console.log(JSON.stringify(data))
				// #ifdef APP-PLUS  
				var webView = this.$mp.page.$getAppWebview();
				// https://uniapp.dcloud.io/collocation/pages?id=app-titlenview-searchinput
				// 动态修改原生导航栏: https://ask.dcloud.net.cn/article/35374
				webView.setTitleNViewButtonStyle(0, {  
					text: data.originalData.result.addressComponent.city,  
				}); 
				// #endif 
			} 
			// 发起regeocoding检索请求 
			BMap.regeocoding({ 
				address: "北京市海淀区上地十街10号", 
				fail: fail, 
				success: success 
			}); 
			 
			// this.getSeckillGoodsList();
			// this.loadData();
			// ---------------------新接口---------------------
			this.getAllBox();
		},
		//下拉刷新
		onPullDownRefresh() {
			this.seckillGoodsList = [];
			this.mallGoodsList = [];
			this.getSeckillGoodsList("refrash");
			this.loadData("refrash");
		},
		methods: {
			getUrlParam:function(name){
					// let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
					// let r = window.location.search.substr(1).match(reg);
					// console.log(9999,reg)
					// if (r != null) {
					// 	return unescape(r[2]);
					// }
					// return null;
					
					
					
					
					let reg = new RegExp('(^|&)code=([^&]*)(&|$)')
					let r = window.location.search.substr(1).match(reg)
					if (r != null) {
						let code = unescape(r[2])
						// let res = await $http.get('wxlogin', {
						// 	'code': code
						// });
					}
					console.log(9999,window.location.search)
				},
			aaa:function(){
					 console.log('代码来源：https://blog.csdn.net/ltns_li/article/details/108850313')
				// if (isWechat()) {
					let code = this.getUrlParam("code"); //是否存在code 截取code代码 授权会返回code需要截取链接中code
					// let local = window.location.href;
					let local = encodeURIComponent('https://0500.t1.nethhw188.com/h5');
					if (code == null || code === "") {
						
						console.log(11111111111111,code)
						//不存在就打开上面的地址进行授权
						// window.location.href =
						// 	'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxad6693c63cdd7ff6&redirect_uri='+local+'&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect';
					//appid填写你的appid 	redirect_uri填写请求成功后回调地址						
					} else {
						that.code = code;
						//把code传给后端判断用户是否关注相对应的公众号
						console.log(222222222222222222222222,code)
						// this.$Request.get(this.$api.home.MallGoodsByClass).then(res => {
						// 	this.mallGoodsList = res.data;
						// 	if (type == "refrash") {
						// 		uni.stopPullDownRefresh();
						// 	}
						// },err => {
						// 	console.log("err: " + JSON.stringify(err));
						// });
						
						
						
						
						
						// uni.request({
						// 	url: 'url',
						// 	header: {
						// 		'content-type': 'application/x-www-form-urlencoded'
						// 	},
						// 	data: {
						// 		code: that.code
						// 	},
						// 	method: 'GET',
						// 	success: (res) => {
						// 		//201没有关注公众号 跳转关注页面
						// 		if (res.data == 201) {
						// 			window.location.href =
						// 				`https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=wechatbiz#wechat_redirect`;
						// 			//_biz的获取通过登录微信公众平台 在头像那里右击查看源码 找到 uin: "658565",uin_base64: ""，_biz的值等于uin_base64就可以了
						// 		} else { //关注了可以进行下一步
						// 			uni.request({
						// 				url: 'url',
						// 				header: {
						// 					'content-type': 'application/x-www-form-urlencoded'
						// 				},
						// 				method: 'GET',
						// 				success: (ti) => {
										
						// 				}
						// 			})
						// 		}
						// 	},
						// })
					}
				// }else{
				// 	uni.showModal({
				// 		title:'请在微信打开',
				// 		content:'请在微信打开本网页'
				// 	})
				// }
			},
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
		
			
			
			
			
			
			
			
			getWxNews(){
				// let local = encodeURIComponent(window.location.href);  //获取当前页面地址
				// window.location.href =
				// 	"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
				// 	Appid +  wxad6693c63cdd7ff6
				// 	"&redirect_uri=" +
				// 	local +
				// 	"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			
			},
			toSearch(){
				let that = this;
				// 原本是跳到搜索页面去搜索的
				// uni.navigateTo({
				// 	url: '/pages/search/search'
				// })
				// 现在是直接跳到列表页面搜索
				uni.navigateTo({
					url: '../product/list?key=' + that.searchKey,
				})
			},
			
			getSeckillGoodsList(type) {
				this.$Request.get(this.$api.home.SeckillGoods).then(res => {
					this.seckillGoodsList = res.data;
					if (type == "refrash") {
						uni.stopPullDownRefresh();
					}
				},err => {
					console.log("err: " + JSON.stringify(err));
				});
			},
			loadData(type) {
				let notLoading = false;
				if (type == "refrash") {
					notLoading = true;
				}
				this.$Request.get(this.$api.home.MallGoodsByClass).then(res => {
					this.mallGoodsList = res.data;
					if (type == "refrash") {
						uni.stopPullDownRefresh();
					}
				},err => {
					console.log("err: " + JSON.stringify(err));
				});
			},
			/**
			 * 爆款监听image加载完成
			 * @param {Object} key
			 * @param {Object} index
			 */
			onImageLoad(key, index) {
				this.$set(this[key][index], 'loaded', 'loaded');
			},
			/**
			 * 爆款监听image加载失败
			 * @param {Object} key
			 * @param {Object} index
			 */
			onImageError(key, index) {
				this[key][index].DefaultPicURL = '/static/errorImage.jpg';
			},

			/**
			 * 分类楼层监听image加载完成
			 * @param {Object} key
			 * @param {Object} index
			 * @param {Object} index2
			 */
			onFloorImageLoad(key, index, index2) {
				this.$set(this[key][index].MallGoodsList[index2], 'loaded', 'loaded');
			},
			/**
			 *  分类楼层监听image加载失败
			 * @param {Object} key
			 * @param {Object} index
			 * @param {Object} index2
			 */
			onFloorImageError(key, index, index2) {
				this[key][index].MallGoodsList[index2].DefaultPicURL = '/static/errorImage.jpg';
			},

			//轮播图切换修改背景色
			swiperChange(e) {
				const index = e.detail.current;
				this.swiperCurrent = index;
				// #ifndef MP
				// this.titleNViewBackground = this.carouselList[index].background;
				// #endif
			},
			navToList(key){
				uni.navigateTo({
					url: `/pages/product/list?key=${key}`
				})
			},
			//详情页
			navToDetailPage(item) {
				//为了模拟数据，正常项目里按照业务传值
				uni.navigateTo({
					url: `/pages/product/detail?goods=${this.$utils.putExtra(item)}`
				})
			},
			// ---------------------------------------------新---------------------------------------------
			getAllBox() {
				let that = this;
				that.$Request.get(that.$api.index.indexAll).then(res => {
						that.carouselList = res.data[0].data;//banner图
						that.navBtn = res.data[2].data;//导航
						that.seckillGoodsList = res.data[5].data//热销推荐
					console.log(that.carouselList,'新首页接口获取',res)
				},err => {
					console.log("err: " + JSON.stringify(err));
				});
			},
			appLoginWx(){
			                // #ifdef MP-WEIXIN
			                    uni.getProvider({
			                      service: 'oauth',
			                      success: function (res) {
			                        if (~res.provider.indexOf('weixin')) {
			                            uni.login({
			                                provider: 'weixin',
			                                success: (res2) => {
			                                    
			                                    uni.getUserInfo({
			                                        provider: 'weixin',
			                                        success: (info) => {//这里请求接口
			                                            console.log(res2);
			                                            console.log(info);
			                                            
			                                        },
			                                        fail: () => {
			                                            uni.showToast({title:"微信登录授权失败",icon:"none"});
			                                        }
			                                    })
			                            
			                                },
			                                fail: () => {
			                                    uni.showToast({title:"微信登录授权失败",icon:"none"});
			                                }
			                            })
			                            
			                        }else{
			                            uni.showToast({
			                                title: '请先安装微信或升级版本',
			                                icon:"none"
			                            });
			                        }
			                      }
			                    });
			                    //#endif
			            }
		},
		// 标题栏input搜索框点击
		onNavigationBarSearchInputClicked: async function(e) {
			uni.navigateTo({
				url: '/pages/search/search'
			})
		},
		//点击导航栏 buttons 时触发
		onNavigationBarButtonTap(e) {
			const index = e.index;
			if (index === 0) {
				this.$utils.showMsg('点击位置');
			} else if (index === 1) {
				// #ifdef APP-PLUS
				const pages = getCurrentPages();
				const page = pages[pages.length - 1];
				const currentWebview = page.$getAppWebview();
				currentWebview.hideTitleNViewButtonRedDot({
					index
				});
				// #endif
				uni.navigateTo({
					url: '/pages/notice/notice'
				})
			}
		},
	}
</script>

<style lang="scss">
	page {
		background: #f5f5f5;
	}

	.m-t {
		margin-top: 16upx;
	}
	/* #ifdef MP */
	.search{
		background: #D22B19;
		padding: 20rpx 0;
	}
	.ser-input {
		// position: absolute;
		// top: 8rpx;
		width: 96%;
		margin-left: 2%;
		text-align: center;
		height: 66upx;
		line-height: 66upx;
		text-align: center;
		font-size: 28upx;
		color: $font-color-base;
		border-radius: 20px;
		background: rgba(255, 255, 255,1);
	}
	/* #endif */
	
	/* 头部 轮播图 */
	.carousel-section {
		position: relative;
		// padding-top: 10px;
		

		// .titleNview-placing {
		// 	height: var(--status-bar-height);
		// 	/* #ifndef MP */
		// 	padding-top: 44px;
		// 	/* #endif */
		// 	box-sizing: content-box;
		// }

		.titleNview-background {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			/* #ifdef MP */
			height: 300upx;
			/* #endif */
			/* #ifndef MP */
			height: 374upx;
			/* #endif */
			transition: .4s;
		}
	}

	.carousel {
		width: 100%;
		height: 294upx;
		// margin-top: 10rpx;
		.carousel-item {
			width: 100%;
			height: 100%;
			// padding: 0 28upx;
			overflow: hidden;
		}

		image {
			width: 100%;
			height: 100%;
			border-radius: 10upx;
		}
	}

	.swiper-dots {
		display: flex;
		position: absolute;
		left: 336upx;
		bottom: 50upx;
		width: 72upx;
		height: 36upx;
		background-image: url();
		background-size: 100% 100%;

		.num {
			width: 36upx;
			height: 36upx;
			border-radius: 50px;
			font-size: 24upx;
			color: #fff;
			text-align: center;
			line-height: 36upx;
		}

		.sign {
			position: absolute;
			top: 0;
			left: 50%;
			line-height: 36upx;
			font-size: 12upx;
			color: #fff;
			transform: translateX(-50%);
		}
	}
.content{
	margin-top: -40rpx;
	background: #f2f2f2;
	position: relative;
	z-index: 6;
	border-radius: 40rpx 40rpx 0px 0px;
	overflow: hidden;
}
	
	/* 分类 */
	.cate-section {
		display: flex;
		justify-content: space-around;
		align-items: center;
		flex-wrap: wrap;
		padding: 30upx 22upx;
		background: #fff;

		.cate-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			font-size: $font-sm + 2upx;
			color: $font-color-dark;
		}

		/* 原图标颜色太深,不想改图了,所以加了透明度 */
		image {
			width: 88upx;
			height: 88upx;
			margin-bottom: 14upx;
			border-radius: 50%;
			opacity: .7;
			box-shadow: 4upx 4upx 20upx rgba(250, 67, 106, 0.3);
		}
	}

	/* 爆款专区 */
	.seckill-section {
		padding: 4upx 30upx 24upx;
		background: #fff;

		.s-header {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 92upx;
			line-height: 1;

			.s-img {
				width: 40upx;
				height: 40upx;
			}

			.tip {
				font-size: $font-lg +2upx;
				color: #font-color-dark;
				line-height: 1.3;
				margin: 0 20upx 0 40upx;
			}

			.icon-you {
				font-size: $font-lg;
				color: $font-color-light;
				flex: 1;
				text-align: right;
			}
		}

		.floor-list {
			white-space: nowrap;
			width: 690upx;
		}

		.scoll-wrapper {
			display: flex;
			align-items: flex-start;
			display: inline-block;
			width: 690upx;
		}

		.floor-item {
			width: 155upx;
			margin-right: 20upx;
			font-size: $font-sm+2upx;
			color: $font-color-dark;
			line-height: 1.8;
			display: inline-block;

			// image {
			// 	width: 155upx;
			// 	height: 155upx;
			// 	border-radius: 6upx;
			// }
			.image-wrapper {
				width: 155upx;
				height: 155upx;
				flex-shrink: 0;
				position: relative;

				image {
					border-radius: 8upx;
				}
			}

			.price {
				color: $uni-color-primary;
			}
		}
	}

	.f-header {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100upx;
		padding: 6upx 30upx 8upx;
		// background: #fff;

		image {
			flex-shrink: 0;
			width: 50upx;
			height: 50upx;
			margin-right: 20upx;
		}

		.tit-box {
			// flex: 1;
			display: flex;
			flex-direction: column;
		}

		.tit {
			font-size: $font-lg +2upx;
			color: #font-color-dark;
			line-height: 1.3;
		}

		.tit2 {
			font-size: $font-sm;
			color: $font-color-light;
		}

		.icon-you {
			font-size: $font-lg +2upx;
			color: $font-color-light;
		}
	}

	/* 分类推荐楼层 */
	.class-floor {
		width: 100%;
		overflow: hidden;
		margin-bottom: 20upx;
		margin-top: -50upx;

		.title {
			font-size: $font-sm+2upx;
			color: $font-color-dark;
			margin-top: 10rpx;
		}

		.subtitle {
			font-size: $font-sm;
			color: $font-color-light;
			line-height: 2.4;
		}

		.price {
			color: $uni-color-primary;
			font-size: $font-lg;
		}

		/* 猜你喜欢 */
		.guess-section {
			display: flex;
			flex-wrap: wrap;
			width: 750upx;
			background: #f2f2f2;
			margin-top: 40rpx;

			.guess-item {
				display: flex;
				flex-direction: column;
				background: #fff;
				width: 46vw;
				margin: 2vw;
				padding: 3vw;
				border-radius: 20rpx;
			}

			.image-wrapper {
				// width: 230upx;
				height: 260upx;
				flex-shrink: 0;
				position: relative;

				image {
					border-radius: 8upx;
				}
			}

			// image {
			// 	width: 230upx;
			// 	height: 260upx;
			// 	opacity: 1;
			// 	
			// }
		}
	}
</style>
